package com.newfiber.business.service.impl;

import com.newfiber.business.api.domain.ScreenMapLayer;
import com.newfiber.business.api.domain.request.ScreenMapLayTypeRequest;
import com.newfiber.business.api.service.IScreenMapLayerService;
import com.newfiber.business.enums.EScreenMapLayerType;
import com.newfiber.common.core.utils.SpringUtils;
import com.newfiber.common.security.utils.ConfigUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author : X.K
 * @since : 2023/10/7 上午10:19
 */
@Slf4j
@Service
public class ScreenMapLayerServiceImpl{

	public List<ScreenMapLayer> parseScreenMapLayer() {
		List<ScreenMapLayer> screenMapLayerList = new ArrayList<>();

		// 按service分组解析图例数据
		Map<Class<? extends IScreenMapLayerService>, List<EScreenMapLayerType>> screenMapLayerTypeMap = Arrays.stream(EScreenMapLayerType.values()).filter(t ->
			null != t.getBusinessService()).collect(Collectors.groupingBy(EScreenMapLayerType::getBusinessService));

		for(Entry<Class<? extends IScreenMapLayerService>, List<EScreenMapLayerType>> entry : screenMapLayerTypeMap.entrySet()){
			try {
				IScreenMapLayerService screenMapLayerService = SpringUtils.getBean(entry.getKey());
				List<ScreenMapLayTypeRequest> screenMapLayTypeRequestList = buildRequest(entry.getValue());
				List<ScreenMapLayer> subScreenMapLayerList = screenMapLayerService.parseScreenMapLayer(screenMapLayTypeRequestList);
				screenMapLayerList.addAll(subScreenMapLayerList);
			}catch (Exception e){
				log.error("图例{}解析错误", entry.getKey().getSimpleName());
				e.printStackTrace();
			}

		}

		List<EScreenMapLayerType> nullScreenMapLayerType = Arrays.stream(EScreenMapLayerType.values()).filter(t -> null == t.getBusinessService()).collect(Collectors.toList());
		for(EScreenMapLayerType screenMapLayerType : nullScreenMapLayerType){
			screenMapLayerList.add(new ScreenMapLayer(screenMapLayerType.getLayerType(), screenMapLayerType.getLayerName()));
		}

		String iconPrefix = ConfigUtils.getConfig("iconPrefixUrl");
		screenMapLayerList.forEach(t -> t.setIconUrl(iconPrefix.concat(t.getLayerName()).concat(".png")));

		return screenMapLayerList;
	}

	private List<ScreenMapLayTypeRequest> buildRequest(List<EScreenMapLayerType> screenMapLayerTypeList){
		List<ScreenMapLayTypeRequest> screenMapLayTypeRequestList = new ArrayList<>();
		for(EScreenMapLayerType screenMapLayerType : screenMapLayerTypeList){
			screenMapLayTypeRequestList.add(new ScreenMapLayTypeRequest(screenMapLayerType.getLayerType(), screenMapLayerType.getLayerName(), screenMapLayerType.getBusinessType()));
		}
		return screenMapLayTypeRequestList;
	}
}
